package com.xinyue.game.server.system;

import com.xinyue.game.server.common.GameServerConfig;
import com.xinyue.network.codec.GameMessageContext;
import com.xinyue.network.codec.GameMessageHeader;
import com.xinyue.network.hamdlermapping.GameChannelContext;
import com.xinyue.network.hamdlermapping.GameHandlerMappingService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public class GameLogicHandler extends ChannelInboundHandlerAdapter {
    private ApplicationContext appContext;
    private Logger logger = LoggerFactory.getLogger(GameLogicHandler.class);
    private GameServerBoot gameServerBoot;
    private GameServerConfig serverConfig;

    public GameLogicHandler(ApplicationContext appContext) {
        this.appContext = appContext;
        gameServerBoot = appContext.getBean(GameServerBoot.class);
        this.serverConfig = appContext.getBean(GameServerConfig.class);
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        GameMessageContext gameMessageContext = (GameMessageContext) msg;
        GameHandlerMappingService gameHandlerMappingService = gameServerBoot.getGameHandlerMappingService();
        GameMessageHeader header = gameMessageContext.getHeader();
        int messageId = header.getMessageId();
        int messageType = header.getMessageType();
        GameChannelContext gtx = new GameChannelContext(ctx, gameMessageContext);
        gameHandlerMappingService.callMethod(gtx, messageId, messageType, gameMessageContext.getGameMessage());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //接收channel内部的一些事件
        logger.debug("channel event :{}", evt.getClass().getName());
        if (evt instanceof IdleStateEvent) {
            logger.debug("channel idle and to be close,{}", ctx.channel().id().asShortText());
            ctx.channel().close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("服务器内部异常", cause);
    }
}
